package com.xiaoxu.privatechat.service.admin;

import com.xiaoxu.privatechat.bean.PageBean;
import com.xiaoxu.privatechat.dao.admin.DatabaseBakDao;
import com.xiaoxu.privatechat.entity.admin.DatabaseBak;
import com.xiaoxu.privatechat.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;


/**
 * @author xiaoxu
 * @description 数据库备份service
 * @date 2023/2/13
 */
@Service
public class DatabaseBakService {

    @Resource
    private OperaterLogService operaterLogService;
    @Resource
    private DatabaseBakDao databaseBakDao;
    @Value("${ylrc.database.backup.dir}")
    private String backUpDir;
    @Value("${ylrc.database.backup.username}")
    private String dbUsername;
    @Value("${ylrc.database.backup.password}")
    private String dbPwd;
    @Value("${ylrc.database.backup.database.name}")
    private String dbName;

    private final Logger log = LoggerFactory.getLogger(DatabaseBakService.class);

    /**
     * @param pageBean 分页
     * @return PageBean<DatabaseBak>
     * @description 分页查找数据库备份记录
     */
    public PageBean<DatabaseBak> findList(PageBean<DatabaseBak> pageBean) {
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage() - 1, pageBean.getPageSize());
        Page<DatabaseBak> findAll = databaseBakDao.findAll(pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }

    /**
     * @param databaseBak 数据备份
     * @return DatabaseBak
     * @description 添加或修改数据库备份记录
     */
    public DatabaseBak save(DatabaseBak databaseBak) {
        return databaseBakDao.save(databaseBak);
    }

    /**
     * @param id 备份id
     * @return DatabaseBak
     * @description 根据id查询
     */
    public DatabaseBak find(Long id) {
        return databaseBakDao.find(id);
    }

    /**
     * @param id 备份id
     * @description 根据id删除
     */
    public void delete(Long id) {
        databaseBakDao.deleteById(id);
    }

    /**
     * @description 备份数据库
     */
    public void backup() {
        try {
            File path = new File(backUpDir);
            if (!path.exists()) {
                boolean Bool = path.mkdir();
                if (!Bool) {
                    throw new IOException("資料夾創建失敗");
                }
            }
            //文件名
            String filename = dbName + "_" + StringUtil.getFormatterDate(new Date(), "yyyyMMddHHmmss") + ".sql";
            //指令
            String cmd = "mysqldump -u" + dbUsername + " -p" + dbPwd + " " + dbName + " -r " + backUpDir + filename;
            //执行指令
            Runtime.getRuntime().exec(cmd);
            //备份数据库信息
            DatabaseBak databaseBak = new DatabaseBak();
            databaseBak.setFilename(filename);
            databaseBak.setFilepath(backUpDir);
            save(databaseBak);
            log.info("数据库备份成功");
            operaterLogService.add("資料庫成功備份，備份檔案資訊：" + databaseBak);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @description 还原数据库
     * @param id 备份id
     */
    public void restore(Long id) {
        //获取备份信息
        DatabaseBak databaseBak = find(id);
        if (databaseBak != null) {
            try {
                //获取文件名
                String filename = databaseBak.getFilename();
                File file = new File(databaseBak.getFilepath() + databaseBak.getFilename());
                //指令
                String cmd = "mysql -u" + dbUsername + " -p" + dbPwd + " " + dbName + " < " + backUpDir + filename;
                if (!file.exists()) {
                    //文件存在指令
                    cmd = "mysql -u" + dbUsername + " -p" + dbPwd + " " + dbName + " < " + databaseBak.getFilepath() + databaseBak.getFilename();
                }
                String stmt1 = "mysqladmin -u " + dbUsername + " -p" + dbPwd + " create " + dbName;
                String[] cmds = {"cmd", "/c", cmd};
                //运行指令
                Runtime.getRuntime().exec(stmt1);
                //运行指令
                Process exec = Runtime.getRuntime().exec(cmds);
                log.info(StringUtil.getStringFromInputStream(exec.getErrorStream()));
                log.info("数据库还原成功");
                operaterLogService.add("資料庫成功還原，還原檔案資訊：" + databaseBak);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * @description 备份总数
     * @return long
     */
    public long total() {
        return databaseBakDao.count();
    }
}
